/*
 * piece.cc
 * This file is part of Quarto
 *
 * Copyright (C) 2012 - Ian Liu Rodrigues <ian.liu88@gmail.com>
 *
 * Quarto is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Quarto is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Quarto. If not, see <http://www.gnu.org/licenses/>.
 */

#include "piece.hpp"

#define FLAGS_MASK 0xf

using namespace br_unicamp;

Piece::Piece(unsigned char flags) {
  this->flags = flags & FLAGS_MASK;
}

Piece::Piece(const Piece& piece) {
  this->flags = piece.flags & FLAGS_MASK;
}

unsigned char Piece::getFlags() const {
  return this->flags;
}

static std::string map[16] = {
  "[W;", "(W;", "[W!", "(W!", // 0000 0001 0010 0011
  "[B;", "(B;", "[B!", "(B!", // 0100 0101 0110 0111
  "[w;", "(w;", "[w!", "(w!", // 1000 0001 1010 1011
  "[b;", "(b;", "[b!", "(b!"  // 1100 1101 1110 1111
};

std::string Piece::toString() const {
  return map[this->flags];
}

bool Piece::isSimilar(const Piece& p1, const Piece& p2)
{
  unsigned char a, b, x;

  a = p1.getFlags();
  b = p2.getFlags();

  x = (a ^ b);

  return (x & 0xf) != 0xf;
}

PieceBag::PieceBag(void)
{
  for (int i = 0; i < 16; i++)
    pieces[i] = this->createPiece(i);
}

PieceBag::~PieceBag(void)
{
  for (int i = 0; i < 16; i++)
    if (pieces[i])
      delete pieces[i];
}

Piece *PieceBag::createPiece(unsigned char code) const
{
  return new Piece(code);
}

void PieceBag::remove(const Piece& piece)
{
  for (int i = 0; i < 16; i++) {
    if (pieces[i] && piece.getFlags() == pieces[i]->getFlags()) {
      delete pieces[i];
      pieces[i] = 0;
    }
  }
}

bool PieceBag::contains(unsigned char code) const
{
  for (int i = 0; i < 16; i++)
    if (pieces[i] && pieces[i]->getFlags() == code)
      return true;
  return false;
}

const Piece* PieceBag::get(int i) const
{
  return pieces[i];
}

const Piece* PieceBag::find(unsigned char code) const
{
  for (int i = 0; i < 16; i++)
    if (pieces[i] && pieces[i]->getFlags() == code)
      return pieces[i];
  return 0;
}
